<?php
namespace Admin\Service;
use Think\Model;
/**
 * 后台用户基础服务：访问权限审核、操作日志记录
 */

class UserService extends Model
{
    const ADMIN_RIGHT = 'admin';
    const DATA_ADMIN = 'DATA_ADMIN';
    const CACHE_KEY = 'xmlright';

    /**
     * 根据用户ID获取用户权限
     * 
    */
    public function getRightById( $uid , $role_id = false)
    {
          $content = array();
          $role = $role_id;
          if ($uid&&!$role_id){
                $MUser = D('Admin/User');
                $role = $MUser->where('user_id='.$uid)->getField('role_id');
                if (!$role)
                   $role =0;
          }
          if ($uid){
            $Mdo = D("Admin/RoleRights");
            $Mxml = D("Admin/Right");
            $rightCfg = $Mxml->xml2arr();
            $wheres = array();
            $wheres['_string'] = '1=1';
            if (1!=$uid)
                $wheres['role_id'] = array('eq', $role );
            $_arr = $Mdo->field("right_id")->where( $wheres )->select();
            $rights = array();
            foreach( $_arr as $v){
                  $rights[] = $v['right_id'];
            }
            $rightdata = array();
            if( $_arr && is_array( $_arr ) && count( $_arr) ){
                  $wheres = array();
                  $wheres['right_id'] = array('in', $rights );
                  $_rightdata = M("Right")->field("right_id,code,right_content")->where( $wheres )->select();
                  foreach( $_rightdata as $v ){
                  if( $v['code'] == self::ADMIN_RIGHT){
                        $res['rcode'] = 1;
                        $res['is_admin'] = true;
                        return $res;
                  }
                  $rightdata[] = $v;
                  }
            }

            $rconfig = array();
            if ( $rightdata ){
                  foreach( $rightdata as $vd ){
                        $im = unserialize( $vd['right_content']);
                        if( $im && is_array($im)  && count( $im ) ){
                              $content = array_merge( $im, $content );
                        }
                  }
              }
          }
          
          return $content;
    }

    /**
     * 用户后台权限访问审核
     * @param  int     $uid        后台用户账号ID
     * @param  int     $role_id    岗位ID
     * @return mixed
     */
    public function auth( $uid, $role_id ){
        $res = array('rcode'=>0,'data'=>false,'is_admin'=>false,'msg'=>'403 Forbidden');

        $content = $this->getRightById($uid, $role_id );

            $controller = CONTROLLER_NAME;
            $action = ACTION_NAME;
            $controller = strtolower( $controller );
            $action = strtolower( $action );
            switch ( $controller ){
                    case 'productline':   //产品线管理
                        if($action == 'index')
                        {
                                if($content['PRODUCTLINE_VIEW'])
                                    $check = TRUE;
                        }
                        break;
                    case 'product':     //产品管理
                        if(in_array( $action ,array('index','getproductline','checknameexist','getteacherinfo')))
                        {
                                if( isset( $content['PRODUCT_VIEW']))
                                    $check = TRUE;
                        }
                        else if( in_array( $action , array('editproduct','addproduct','getuserinfo')))
                        {
                                if( isset( $content['PRODUCT_CAOZUO']))
                                    $check = TRUE;
                        }
                        else if( $action == 'delproduct')
                        {
                                if( $content['PRODUCT_DELATE'])
                                    $check = TRUE;
                        }
                        break;
                    case 'productpackage':     //产品套餐管理
                        if(in_array( $action ,array('index','getproductline','getproduct','getlinecode','checknameexist','checkcodeexist','getqyservice','getservof')))
                        {
                                if( isset( $content['PRODUCTPACKAGE_VIEW']))
                                    $check = TRUE;
                        }
                        else if( in_array( $action , array('editpackage','addpackage')))
                        {
                                if( isset( $content['PRODUCTPACKAGE_CAOZUO']))
                                    $check = TRUE;
                        }
                        else if( $action == 'delpackage')
                        {
                                if( $content['PRODUCTPACKAGE_DELATE'])
                                    $check = TRUE;
                        }
                        break;
                    case 'qyservice':  //套餐服务
                        if($action == 'index')
                        {
                                if( isset( $content['QYSERVICE_VIEW']))
                                    $check = TRUE;
                        }
                        else if( in_array( $action , array('addservice','editservice')))
                        {
                                if( isset( $content['QYSERVICE_CAOZUO']))
                                    $check = TRUE;
                        }
                        else if( $action == 'delservice')
                        {
                                if( $content['QYSERVICE_DELATE'])
                                    $check = TRUE;
                        }
                        break;
                    case 'money':       //财务管理
                        if( in_array( $action , array('index','catchuid','paytypes','getcreator','statistics')))
                        {
                                if(  isset( $content['MONEY_VIEW']))
                                    $check = TRUE;
                        }
                        else if( in_array( $action , array('auditverify')))
                        {
                                if( isset( $content['MONEY_VERIFY']))
                                    $check = TRUE;
                        }
                        else if( in_array( $action , array('getrecord','verfed','refund','refundview','refundconfirm')))
                        {
                            if( isset( $content['MONEY_REFUND']))
                                    $check = TRUE;
                            else if( isset( $content['MONEY_VIEW'])) {
                                    $check = TRUE;
                            }
                        }
                        break;
                case 'pays':        //查账管理
                    if( in_array( $action , array('index','products','paytypes','products')) ){
                        $check = TRUE;
                    }else if( in_array( $action , array('addnew')))
                    {
                        if(  isset( $content['PAYS_ADD']))
                                $check = TRUE;
                    }
                    break;
                case 'contract':    //合同管理
                    if( in_array( $action , array('index','productdata','mail', 'sweepdetection', 'checkcustomer')))
                    {
                            if( isset( $content['CONTRACT_VIEW']) )
                                $check = TRUE;
                    }
                    else if( in_array( $action , array('editor','cancel','merge_editor','merge_show','editorshow')))
                    {
                            if( isset( $content['CONTRACT_CAOZUO'])) {
                                $check = TRUE;
                            }
                    }else if(in_array( $action ,array('export_contract'))) {
                            if( isset( $content['CONTRACT_EXPORT'])) {
                                $check = TRUE;
                            }
                    }else if( in_array( $action , array('batch_editor'))){
                            if( isset( $content['CONTRACT_DELIVERY_EDIT'])) {
                                $check = TRUE;
                            }
                    }else if( in_array( $action , array('export_violations'))){
                            if( isset( $content['WEIGUI_EXPORT'])) {
                                $check = TRUE;
                            }
                    }
                    else if(in_array($action, array('econtract','batchecontract'))){
                            if (isset($content['WEIGUI_ECONTRACT'])) {
                                $check = TRUE;
                            }
                    }
                    break;
                case 'right':       //权限
                    if( in_array( $action , array('index','getconfig')))
                    {
                            if( isset( $content['RIGHT_VIEW']) )
                                $check = TRUE;
                    }
                    else if( in_array( $action , array('add','edit','delete')))
                    {
                            if( isset( $content['RIGHT_EDIT']))
                                $check = TRUE;
                    }
                case 'role':        //岗位管理
                    if( $action == 'index')
                    {
                            if( isset( $content['ROLE_VIEW']))
                                $check = TRUE;
                    }
                    else if( in_array( $action , array('add','edit')))
                    {
                            if( isset( $content['ROLE_CAOZUO']) )
                            $check = TRUE;
                    }
                    break;
                case 'sector':      //部门管理
                    if( $action == 'index')
                    {
                            $check = TRUE;
                    }
                    else if( in_array( $action , array('add','edit','delete')))
                    {
                            if( isset( $content['SECTOR_EDIT']) )
                                $check = TRUE;
                    }
                    break;
                case 'event':       //日程管理
                    if( in_array( $action, array('index')))
                    {
                            $check = TRUE;
                    }
                    else if( in_array( $action , array('add','edit')))
                    {
                        if( isset( $content['EVENT_CAOZUO']) )
                            $check = TRUE;
                    }
                    else if( in_array( $action , array('remove')))
                    {
                        if( isset( $content['EVENT_DELETE']) )
                            $check = TRUE;
                    }
                    else if( in_array( $action , array('showusers')))
                    {
                        if( isset( $content['EVENT_SELECT']) )
                            $check = TRUE;
                    }
                    break;
                case 'log':         //日志管理
                    if( $action == 'index')
                    {
                            $check = TRUE;
                    }
                    else if(in_array( $action , array('add','edit')) )
                    {
                        if( isset($content['LOG_CAOZUO']))
                                $check = TRUE;
                    }
                    else if( $action == 'remove')
                    {
                        if( isset($content['LOG_DELETE']))
                                $check = TRUE;
                    }
                    else if( $action == 'reviewlist')
                    {
                        if( isset($content['LOG_SHENHE']))
                                $check = TRUE;
                    }
                    else if(in_array( $action , array('reviewok','reviewno')))
                    {
                        if( isset($content['LOG_SHENHE_CAOZUO']))
                                $check = TRUE;
                    }
                    else if(in_array( $action , array('getaudit','getuname')) )
                    {
                        if( isset($content['LOG_SHENHE_VIEW']))
                                $check = TRUE;
                    }
                    break;
                case 'user':        //员工管理
                    if(in_array( $action , array('searchbyname','searchcustomername')))         $check = TRUE;
                    if(in_array( $action , array('index','getpageparam')) )
                    {
                        if( isset($content['USER_VIEW']))
                                $check = TRUE;
                    }
                    else if(in_array( $action , array('resetpass','changerolesector','saveedit')))
                    {
                        if( isset($content['USER_CAOZUO']))
                                $check = TRUE;
                    }
                    else if( $action == 'userdelall')
                    {
                        if( isset($content['USER_DELETE']))
                                $check = TRUE;
                    }
                    break;
                case 'goals':       //营销目标
                    if(in_array( $action ,array('getobject'))){
                            $check = TRUE;
                    }
                    else if(in_array( $action ,array('index')))
                    {
                            if( isset( $content['GOALS_VIEW']))
                                $check = TRUE;
                    }
                    else if( in_array( $action , array('editgoal','addgoal')))
                    {
                            if( isset( $content['GOALS_CAOZUO']))
                                $check = TRUE;
                    }
                    break;
                case 'pk':          //PK管理
                    if(in_array( $action ,array('index')))
                    {
                            if( isset( $content['PK_VIEW']))
                                $check = TRUE;
                    }
                    else if( in_array( $action , array('addpk','editpk')))
                    {
                            if( isset( $content['PK_CAOZUO']))
                                $check = TRUE;
                    }
                    else if( $action == 'delshowpk')
                    {
                            if( $content['PK_DELETE'])
                                $check = TRUE;
                    }
                    break;
                case 'tags':        //标签管理
                    if(in_array( $action ,array('index')))
                    {
                            if( isset( $content['TAGS_VIEW']))
                                $check = TRUE;
                    }
                    else if( in_array( $action , array('add','edit','remove')))
                    {
                            if( isset( $content['TAGS_CAOZUO']))
                                $check = TRUE;
                    }
                    else if( $action == 'tagcustomer')
                    {
                            if( $content['TAGS_CUSTOMER_VIEW'])
                                $check = TRUE;
                    }
                    else if( $action == 'removecustomer')
                    {
                            if( $content['TAGS_CUSTOMER_DELETE'])
                                $check = TRUE;
                    }
                    break;
                case 'view360':     //View360
                    if(in_array( $action ,array('getright','editcust')))
                    {
                            $check = TRUE;
                    }
                    else if(in_array( $action ,array('index','customerinfo','contractpays','contracts',
                        'fukuan','checkphone','getfukuan','getcontractlist','getstocks','stocklist',
                        'getphoneinfo','getcontactinfo','getwenjuaninfo')))
                    {       if( isset($content['VIEW360_VIEW']))
                                $check = TRUE;
                    }
                    else if( in_array( $action ,array('addcontact')) )
                    {
                            if( isset($content['VIEW360_CONTACT_CAOZUO']))
                                $check = TRUE;
                    }
                    else if( in_array( $action ,array('getsalesinfo','getsourceinfo','editcust')) )
                    {
                            if( isset($content['VIEW360_BASEEDIT']))
                                $check = TRUE;
                    }
                    else if( in_array( $action ,array('getsalesinfo','getsourceinfo','editcust')) )
                    {
                            if( isset($content['VIEW360_SENSIEDIT']))
                                $check = TRUE;
                    }
                    else if( in_array( $action ,array('getsalepersoninfo','editsalesperson')) )
                    {
                            if( isset($content['VIEW360_SALESPERSONEDIT']))
                                $check = TRUE;
                    }
                    else if(in_array( $action , array('getcomplaininfo','getriskinfo')))
                    {
                            if( isset($content['VIEW360_FENGKONG']))
                                $check = TRUE;
                    }
                    break;
                case 'productprice'://产品报价
                    if(in_array( $action ,array('product_price')))
                    {
                            if( isset( $content['PRODUCT_PRICE_VIEW']))
                                $check = TRUE;
                    }
                    else if( in_array( $action , array('notstandarder','product_price_add','notstandarder','save_product_price')))
                    {
                            if( isset( $content['PRODUCT_PRICE_CAOZUO']))
                                $check = TRUE;
                    }
                    else if( $action == 'product_price_delete')
                    {
                            if( $content['PRODUCT_PRICE_DELETE'])
                                $check = TRUE;
                    }
                    break;
                case 'xufei':       //续费管理
                    if(in_array( $action ,array('index')))
                    {
                            if( isset( $content['XUFEI_VIEW']))
                                $check = TRUE;
                    }
                    else if( in_array( $action , array('tab_select','check_tag','new_tag')))
                    {
                            if( isset( $content['XUFEI_TAG']))
                                $check = TRUE;
                    }
                    else if( in_array( $action , array('change_star','customertypeshow','changecustomertype')) )
                    {
                            if( $content['XUFEI_INFO'])
                                $check = TRUE;
                    }
                    else if( $action == 'addcommunication')
                    {
                            if( $content['XUFEI_CONTACT'])
                                $check = TRUE;
                    }
                    break;
                case 'source':      //渠道管理
                    if(in_array( $action ,array('index','catchuid','getsector1','getsector','mysource')))
                    {
                            if( isset( $content['SOURCE_VIEW']))
                                $check = TRUE;
                    }
                    else if( in_array( $action , array('add','edit')))
                    {
                            if( isset( $content['PRODUCT_CAOZUO']))
                                $check = TRUE;
                    }
                    else if( $action == 'remove')
                    {
                            if( $content['SOURCE_DELETE'])
                                $check = TRUE;
                    }
                    break;
                case 'complain':    //400
                    if(in_array( $action ,array('index','getmessage','getres','showcomplainrecord','hidecomplainrecord','shownorhidden')))
                    {
                            if( isset( $content['COMPLAIN_VIEW']))
                                $check = TRUE;
                    }
                    else if( in_array( $action , array('add','edit')))
                    {
                            if( isset( $content['COMPLAIN_CAOZUO']))
                                $check = TRUE;
                    }else if( in_array($action,array('exportrecords'))) {
                            if( isset( $content['COMPLAIN_DAOCHU']) ) {
                                $check = TRUE;
                            }
                    }
                    break;
                case 'om':          //OM配置
                if(in_array( $action ,array('getcalmsg','getsector')))
                {
                    if(  isset( $content['OM_SHICHANG']))
                        $check = TRUE;
                }
                else if(in_array( $action ,array('index')))
                {
                    if(  isset( $content['OM_HUAWU_VIEW']))
                        $check = TRUE;
                }
                else if(in_array( $action ,array('editom')))
                {
                    if(  isset( $content['OM_HUAWU_CAOZUO']))
                        $check = TRUE;
                }
                else if(in_array( $action ,array('reviewlist')))
                {
                    if(  isset( $content['OM_OM_VIEW']))
                        $check = TRUE;
                }
                else if(in_array( $action ,array('reviewok','reviewno')))
                {
                    if(  isset( $content['OM_OM_CAOZUO']))
                        $check = TRUE;
                }
                else if(in_array( $action ,array('getom','omlist')))
                {
                    if(  isset( $content['OM_FENJI_VIEW']))
                        $check = TRUE;
                }
                else if(in_array( $action ,array('getaudit','getuname','getclerk')))
                {
                    if(  isset( $content['OM_FENJI_CAOZUO']))
                        $check = TRUE;
                }
                break;
                case 'call':        //个人通话管理
                    if(in_array( $action ,array('timestatistics','getchangetrends','calllogs')))
                    {
                            if(  isset( $content['CALL_VIEW']))
                                $check = TRUE;
                    }
                    if(in_array( $action ,array('records')))  $check = true;
                    break;
                case 'analysis':    //查看资源分配统计
                    if(in_array( $action ,array( 'index' ))){
                            $check = TRUE;
                    }
                    break;
                case 'index':       //首页获取部门
                    if($action == 'sector' || $action == 'updateuser'|| $action=='menu') {
                            $check = TRUE;
                    } 
                    break;
                case 'fine':        //罚款单
                    if(in_array($action ,array('index','getfine','isadministrator','getmanager','getsysparam','getuserbyid'))) {
                            if(  isset( $content['FINE_VIEW']))   $check = true;
                    } else if(in_array($action,array('addfine','updatefine','delfine','exportfine'))) {
                            if(  isset( $content['FINE_CAOZUO']))   $check = true;
                    }
                    break;
                case 'violations':  //违规单
                    if( in_array($action,array('index','violations_check'))) {
                            if( isset ($content['VIOLATIONS_VIEW']))    $check = true;
                    } else if(in_array($action,array('cancel','violationsadd','violationseditor','addshow','editor_show','violationscustomer'))) {
                            if( isset ($content['VIOLATIONS_CAOZUO']))  $check = true;
                    } else if(in_array($action,array('import_excel','export_excel'))) {
                            if( isset ($content['VIOLATIONS_EXCEL']))  $check = true;
                    }
                    break;
                case 'delivery':    //邮寄管理
                    if( in_array($action, array('index','communal'))) {
                            if( isset ($content['DELIVERY_VIEW']))    $check = true;
                    } else if(in_array($action,array('deliveryeeditor','confirm_editor','cancel','batch','confirm_show'))) {
                            if( isset ($content['DELIVERY_CAOZUO']))  $check = true;
                    }else if( in_array($action, array('batch_editor'))) {
                            if(isset($content['CONTRACT_DELIVERY_EDIT'])) $check = true;
                    }else if(in_array($action,array('import_delivery','export_delivery'))) {
                            if(isset($content['DELIVERY_EXCEL'])) $check = true;
                    }else if(in_array($action,array('deliveryadd'))) {
                            if(isset($content['CONTRACT_DELIVERY_ADD'])) $check = true;
                    }
                    break;

                case 'qyapp':    //栏目管理
                    if( in_array($action, array('index','productdata','view_details'))) {
                            if( isset ($content['QYAPP_VIEW']))    $check = true;
                    } else if(in_array($action,array('add_admin','sales_peron'))) {
                            if( isset ($content['QYAPP_ADMIN_EDIT']))  $check = true;
                    }else if( in_array($action, array('add_package','product_package'))) {
                            if(isset($content['QYAPP_PACKAGE_EDIT'])) $check = true;
                    }
                    break;
                case 'ordercustomer':    //订户管理
                    if(in_array($action,array('index','getuser','getsubcompany','subscriberforbidden','subscriberdelete','adduser','addstranger','getpackage','getcompanyaccount','wechat_duplicate','phone_duplicate'))) {
                            if( isset ($content['ORDERCUSTOMER_CAOZUO']))    $check = true;
                    } else if(in_array($action,array('modifyuser','modifystranger','modifycustomer','getpackage','edit_phone_duplicate','edit_wechat_duplicate'))) {
                            if( isset ($content['ORDERCUSTOMER_EDIT']))  $check = true;
                    }
                    break;
                case 'customer':    //客户池
                    if($action == 'getfloatinfos')
                    {
                            $check = TRUE;
                    }
                    elseif( in_array($action, array('index')) ) {
                            if( isset ($content['CUSTOMER_VIEW']))    $check = true;
                    }
                    elseif ($action == 'combine') {
                            if( isset ($content['CUSTOMER_COMBINE']))  $check = true;
                    }
                    elseif ($action=='pays_import') {
                        if( isset ($content['CUSTOMER_IMPORT']))  $check = true;
                    }
                    break;
                case 'invoice':     //发票
                    if(in_array($action,array('getpayinfos','getcustomerinfo','add','addimgs','addspecial'))) {
                            if( isset ($content['MONEY_INVOICE'])) {
                                        $check = true;
                            }
                    }
                    if(in_array($action ,array('index','getcustomerinfo','getcustomer','getinvimag','getpayinfos','getcustomername','getcustomerid'))) {
                            if( isset ($content['INVOICE_VIEW'])) {
                                    $check = true;
                            }
                    } else if(in_array($action,array('add','edit','addimgs','addspecial','editspecial','editimg'))) {
                            if( isset ($content['INVOICE_CAOZUO'])) {
                                    $check = true;
                            }
                    } else if(in_array($action,array('invoiceexport'))) {
                            if( isset ($content['INVOICE_DAOCHU']))  $check = true;
                    }
                    break;
                case 'conflict':    //撞单
                    if(in_array($action,array('index','getsector','getcustomerservicepeople','getmsg','getusermsg','getusername','erifycustomerbelong','getcustomername','customerpayrecords','getusermanagermsg','customerbelong','getusermanagername','editconflictmsg'))) {
                            if( isset ($content['CONFLICT_VIEW']))    $check = true;
                    } else if(in_array($action,array('add','exportrecords'))) {
                            if( isset ($content['CONFLICT_CAOZUO']))  $check = true;
                    }
                    break;
                case 'refund':            //退款
                    if(in_array($action,array('options','customer','index'))) {
                            if( isset ($content['REFUND_VIEW']))    $check = true;
                    } else if(in_array($action,array('add','edit','confirm','delete'))) {
                            if( isset ($content['REFUND_CAOZUO'])) {
                                    $check = true;
                            }
                    }else if(in_array( $action ,array('export_popup'))) {
                            if(isset( $content['REFUND_DAOCHU'])) {
                                $check = TRUE;
                            }else if(isset( $content['REFUND_GAOJI'])) {
                                $check = TRUE;
                            }
                    }
                    break;
                case 'qy'://企业号管理
                    if (isset( $content['QY_VIEW'])){
                        $check = true;
                    }
                break;
                case 'knowledgeright': //知识点节点管理
                    if(isset($content['KNOWLEDGE_NODE_MANAGE'])) {
                            $check = TRUE;
                    }
                break;
                case 'knowledgeproperty': //知识点权限管理
                case 'viewknowledgenode'://查看知识库节点权限
                    if(isset($content['KNOWLEDGE_NODE_ARTICLE'])) {
                            $check = TRUE;
                    }
                break;
                case 'risk':        //风险
                    if($action == 'getcustomers')   $check = true;
                    if(in_array($action,array('options','index','getcustomers'))) {
                            if( isset ($content['RISK_VIEW']))    $check = true;
                    } else if(in_array($action,array('close','add','edit','confirm','delete','track','hangup','riskimport','track_new'))) {
                            if( isset ($content['RISK_CAOZUO'])) {
                                    $check = true;
                            }
                    }else if(in_array( $action ,array('riskexport'))) {
                            if(isset( $content['RISK_DAOCHU'])) {
                                $check = TRUE;
                            }else if(isset( $content['RISK_GAOJI'])) {
                                $check = TRUE;
                            }
                    }
                break;
                case 'document':  //个人管理
                    if( $action == 'index' ) {
                        if(isset ($content['DOCUMENT_VIEW'])) $check = true;
                    }else if(in_array($action,array('geteditinfo','editempl'))){
                        if(isset ($content['DOCUMENT_CAOZUO'])) $check = true;
                    } 
                break;
                case 'employee':  //员工管理
                    if(in_array($action,array('index','getpageparam'))){
                        if(isset($content['HR_VIEW'])) $check = true;
                    }else if(in_array($action,array('adduser','saveedit','resetpass','geteditinfo','returnedit'))){
                        if(isset($content['HR_CAOZUO'])) $check = true;
                    }
                break;
                case 'auditing': //档案审核
                    if(in_array($action,array('index','update'))){
                        if(isset($content['HR_CHECK'])) $check = true;
                    }
                break;
                case 'jiangcheng':  //奖惩管理
                    if(in_array($action,arrar('index','getHrPunishData','getHrCommendData','getHrOfferData'))){
                        if(isset($content['HR_JIANGCHENG'])) $check = true;
                    }
                break;
                /*case 'dimission':
                break;*/
            }
            if( !$_rightdata && !$check ){
                    $check = FALSE;
                    if( $controller == 'index')
                    {
                        if( in_array( $action , array('index','psw','saverify','sec'))){
                                $check = TRUE;
                        }
                    }
                    else if( $controller == 'login')
                    {
                        $check = TRUE;
                    }
            }

            if($check){
                $res['rcode'] = 1;
            }

            return $res;
    }

    private function _loadUserRights($uid )
    {
        $Mdo = D("Admin/RoleRights");
        $Mxml = D("Admin/Right");
        $MUser = D('Admin/User');
        $whereu = array();
        $whereu['user_id'] = array('eq', $uid );

        $uinfo = $MUser->where( $whereu )->find();
        //cache XML RIGHT
        $cacheRights = F(self::CACHE_KEY);
        $rightCfg = false;
        if ( $cacheRights )
            $rightCfg = $cacheRights;
        else {
            $rightCfg = $Mxml->xml2arr();
            F(self::CACHE_KEY, $rightCfg );
        }

        if( !$rightCfg || !$uinfo){
            return FALSE;
        }
        if( !$uinfo['role_id'] )
            return FALSE;
        $role_id = $uinfo['role_id'];
        $wheres = array();
        $wheres['role_id'] = array('eq', $role_id );
        $_arr = $Mdo->field("right_id")->where( $wheres )->select();
        $rights = array();
        foreach( $_arr as $v){
            $rights[] = $v['right_id'];
        }
        $rightdata = array();
        if( $_arr && is_array( $_arr ) && count( $_arr) ){
            $wheres = array();
            $wheres['right_id'] = array('in', $rights );
            $_rightdata = M("Right")->field("right_id,code,right_content")->where( $wheres )->select();
            foreach( $_rightdata as $v ){
                $rightdata[] = $v;
            }
        }

        $content = array();
        if( $rightdata ){
            foreach( $rightdata as $vd ){
                $im = unserialize( $vd['right_content']);
                if( $im && is_array($im)  && count( $im ) ){
                    $content = array_merge( $im, $content );
                }
            }
        }

        return $content;
    }

    public function authWithKey($uid, $key )
    {
        $res = array('rcode'=>0, 'msg'=>'');
        if(!$uid || !$key ){
            $res['msg'] = '提交参数错误';
        }
        else {
            $uRights = $this->_loadUserRights( $uid );
            if(!$uRights){
                $res['msg'] = "获取用户权限数据失败";
            }
            else{
                $res['rcode'] = $uRights && isset($uRights[$key]) ? 1:0;
                if ( $res['rcode'])
                    $res['msg'] = 'OK';
                else
                    $res['msg'] = "无权访问";
            }
        }
        return $res;
    }

    /**
     * 通过后台部门自动添加员工
     * @param string $sales_name 销售名称
     * @param string $_team      团队名称
     *
     * @return  array('rcode'=>'','data'=>'','msg'=>'')
     */
    public function addByTeam($sales_name, $_team)
    {
        $res = array('rcode'=>0, 'msg'=>'', 'data'=>array() );
        $MSector = D('Admin/Sector');
        $MUser = D('Admin/User');
        if (!$sales_name || !$_team) {
            $res['msg'] = "参数提交错误";
        }
        else {
            $wheres = array();
            $wheres['is_subcompany'] = array('eq', 1);
            $wheres['sector_name'] = array('eq', $_team);
            $subCompany = $MSector->where( $wheres )->find();
            if ($subCompany) {
                $whereu = array();
                $whereu['u.nickname'] = array('eq', $sales_name );
                $user = $MUser->alias("u")
                              ->field("u.user_id")
                              ->join("LEFT JOIN sector s on s.sector_id=u.sector_id")
                              ->where( $whereu )
                              ->find();
                if ($user) {
                    $res['rcode'] = 1;
                    $res['msg'] = "销售已经存在";
                    $res['data'] = $user['user_id'];
                }
                else {
                    $du = array();
                    $du['nickname'] = $sales_name;
                    $du['role_id'] = 0;
                    $du['sector_id'] = $subCompany['sector_id'];
                    $du['pass'] = '1111';
                    $du['create_time'] = $du['last_time']= date('Y-m-d H:i:s');
                    $du['is_deleted'] = 0;
                    $du['state'] = 0; //禁止登陆
                    $du['login_name'] = 'A'.$MUser->count().$sales_name;
                    $ret = $MUser->data( $du )->add();
                    if ($ret) {
                        $retdata = array();
                        $retdata['user_id'] = $ret;
                        $retdata['sector_id'] = $subCompany['sector_id'];
                        $res['rcode'] = 1;
                        $res['data'] = $retdata;
                        $res['msg'] = 'OK';
                    }
                    else {
                        $res['msg'] = "添加员工数据失败";
                    }
                }
            }
            else {
                $res['msg'] = "分公司数据匹配失败";
            }
        }

        return $res;
    }
      /**
     * 记录员工操作日志
     * @return [type] [description]
     */
    public function log($_param){
          $arrs = array();
          $msgs = '后台用户管理，';
            //日程管理
          if(stristr($_param['request_url'], 'Admin/event/add'))  $msgs = $msgs.'添加日程';
          else if(stristr($_param['request_url'], 'Admin/event/edit')) $msgs = $msgs.'修改日程';
          else if(stristr($_param['request_url'], 'Admin/event/remove')){
            $arrs1 = explode('id=',$_param['request_url']);
            $map1 = array();
            $map1['event_id'] = array('eq',$arrs1[1]);
            $event_title = M('Event')->where($map1)->getField('title');
            $msgs = $msgs.'删除日程'.$arrs1[1].'('.$event_title.')';
          }
            //日志管理
          else if(stristr($_param['request_url'], 'Admin/log/add'))  $msgs = $msgs.'添加日志';
          else if(stristr($_param['request_url'], 'Admin/log/edit')) {
            $arrs2 = explode('log_id=',$_param['request_url']);
            $map2 = array();
            $map2['log_id'] = array('eq',$arrs2[1]);
            $log_title1 = M('Log')->where($map2)->getField('title');
            $msgs = $msgs.'修改日志'.$arrs2[1].'('.$log_title1.')';
          }
          else if(stristr($_param['request_url'], 'Admin/log/remove')) {
            $arrs2 = explode('id=',$_param['request_url']);
            $map2 = array();
            $map2['log_id'] = array('eq',$arrs2[1]);
            $log_title1 = M('Log')->where($map2)->getField('title');
            $msgs = $msgs.'删除日志'.$arrs2[1].'('.$log_title1.')';
          }
          else if(stristr($_param['request_url'], 'Admin/log/reviewok')){
            $map3 = array();
            $arrs3 = D('Log')->str_cut('log_id=','&',$_param['request_url']);
            $map3['log_id'] = array('eq',$arrs3);
            $log_title2 = M('Log')->where($map3)->getField('title');
            $msgs = $msgs.'审核员工日志'.$arrs3.'('.$log_title2.')为通过状态';
          }
          else if(stristr($_param['request_url'], 'Admin/log/reviewno')){
            $map4 = array();
            $arrs4 = D('Log')->str_cut('log_id=','&',$_param['request_url']);
            $map4['log_id'] = array('eq',$arrs4);
            $log_title3 = M('Log')->where($map4)->getField('title');
            $msgs = $msgs.'审核员工日志'.$arrs4.'('.$log_title3.')为未通过状态';
          }
            //权限管理
          else if(stristr($_param['request_url'], 'Admin/right/add'))  $msgs = $msgs.'增加权限';
          else if(stristr($_param['request_url'], 'Admin/right/delete')) $msgs = $msgs.'删除权限';
          else if(stristr($_param['request_url'], 'Admin/right/edit')) {
            $map5 = array();
            $arrs5 = explode('id=',$_param['request_url']);
            $map5['right_id'] = array('eq',$arrs5[1]);
            $right_name = M('Right')->where($map5)->getField('right_name');
            if(strpos($_param['request_url'], 'id'))
              $msgs = $msgs.'修改权限'.$arrs5[1].'('.$right_name.')';
            else $msgs = $msgs.'修改权限';
          }
            //岗位管理
          else if(stristr($_param['request_url'], 'Admin/role/add')) $msgs = $msgs.'添加岗位';
          else if(stristr($_param['request_url'], 'Admin/role/edit?')){
            $map = array();
            $arrs = explode('role_id=',$_param['request_url']);
            $map['role_id'] = array('eq',$arrs[1]);
            $role_name = M('Role')->where($map)->getField('role_name');
            if(strpos($_param['request_url'], 'role_id'))
              $msgs = $msgs.'修改岗位'.$arrs[1].'('.$role_name.')';
            else $msgs = $msgs.'修改岗位';
          }
            //部门管理
          else if(stristr($_param['request_url'], 'Admin/sector/add')) $msgs = $msgs.'添加部门';
          else if(stristr($_param['request_url'], 'Admin/sector/edit'))  $msgs = $msgs.'修改部门信息';
          else if(stristr($_param['request_url'], 'Admin/Sector/delete'))  $msgs = $msgs.'删除部门';
            //员工管理
          else if(stristr($_param['request_url'], 'Admin/user/changeUserPwd')){
            $maps = array();
            $arrss = D('Log')->str_cut('uid=','&',$_param['request_url']);
            $maps['user_id'] = array('eq',$arrss);
            $nickname = M('User')->where($maps)->getField('nickname');
            if(strpos($_param['request_url'], 'uid'))
              $msgs = $msgs.'重置员工'.$arrss.'('.$nickname.')的密码';
            else $msgs = $msgs.'重置员工密码';
          }
          else if(stristr($_param['request_url'], 'Admin/user/changeUserBmGw')){
            $user_id = D('Log')->str_cut('uid=','&sid',$_param['request_url']);
            $sector_id = D('Log')->str_cut('sid=','&rid',$_param['request_url']);
            $role_arr = explode('rid=',$_param['request_url']);
            $role_id = $role_arr[1];
            $map1['user_id'] = array('eq',$user_id);
            $nickname = M('User')->where($map1)->getField('nickname');
            $map2['sector_id'] = array('eq',$sector_id);
            $sector_name = M('Sector')->where($map2)->getField('sector_name');
            $map3['role_id'] = array('eq',$role_id);
            $role_name = M('Role')->where($map3)->getField('role_name');
            $msgs = $msgs.'修改员工'.$nickname.'部门为'.$sector_name.'-'.$role_name;
          }
          else if(stristr($_param['request_url'], 'Admin/user/addUser')) $msgs = $msgs.'添加员工';
          else if(stristr($_param['request_url'], 'Admin/user/saveEdit')) $msgs = $msgs.'修改员工信息';
          else if(stristr($_param['request_url'], 'Admin/user/userDelAll')){
            $ustr_arr = explode('ustr=',$_param['request_url']);
            $usid_arrs = $ustr_arr[1];
            $usid_arr = explode(',',$usid_arrs);
            $msgs = $msgs.'删除用户:';
            for($i=0;$i<count($usid_arr);$i++){
              $maps['user_id'] = array('eq',$usid_arr[$i]);
              $nickname_arr[] = M('User')->where($maps)->getField('nickname');
              $msgs = $msgs.$nickname_arr[$i].'、'; //删除的用户用、分割
            }
            $msgs = substr($msgs,0,strlen($msgs)-1); //去掉最后一个、

          }
            //营销目标
          else if(stristr($_param['request_url'], 'Admin/Goals/editGoal')) $msgs = $msgs.'修改营销目标';
          else if(stristr($_param['request_url'], 'Admin/Goals/addGoal'))  $msgs = $msgs.'添加营销目标';
            //PK管理
          else if(stristr($_param['request_url'], 'Admin/Pk/addPK')) $msgs = $msgs.'添加PK信息';
          else if(stristr($_param['request_url'], 'Admin/Pk/editPK'))  $msgs = $msgs.'修改PK信息';
          else if(stristr($_param['request_url'], 'Admin/Pk/delShowPk')){
            $pkid = explode('pkid=',$_param['request_url']);
            $map['pkid'] = array('eq',$pkid[1]);
            $pk_info = M("sales_pk")->where($map)->find();
            if($pk_info['a_type']==1){  //A方为个人
              $map1['user_id'] = array('eq',$pk_info['a']);
              $a_nickname = M('User')->where($map1)->getField('nickname');
            }else if($pk_info['a_type']==2){  //A方为部门
              $map2['sector_id'] = array('eq',$pk_info['a']);
              $a_nickname = M('Sector')->where($map2)->getField('sector_name');
            }
            if($pk_info['b_type']==1){  //B方为个人
              $map3['user_id'] = array('eq',$pk_info['b']);
              $b_nickname = M('User')->where($map3)->getField('nickname');
            }else if($pk_info['b_type']==2){  //B方为部门
              $map4['sector_id'] = array('eq',$pk_info['b']);
              $b_nickname = M('Sector')->where($map4)->getField('sector_name');
            }
            $msgs = $msgs.'删除'.$a_nickname.'和'.$b_nickname.$pk_info['start_time'].'到'.$pk_info['end_time'].'的PK信息';
          }
            //产品管理
          else if(stristr($_param['request_url'], 'Admin/Product/editProduct'))  $msgs = $msgs.'修改产品';
          else if(stristr($_param['request_url'], 'Admin/Product/delProduct')){
            $pid_arr = explode('id=',$_param['request_url']);
            $map['product_id'] = array('eq',$pid_arr[1]);
            $product_name = M('Product')->where($map)->getField('name');
            $msgs = $msgs.'删除产品'.$pid_arr[1].'('.$product_name.')';
          }
          else if(stristr($_param['request_url'], 'Admin/Product/addProduct')) $msgs = $msgs.'添加产品';
            //客户标签
          else if(stristr($_param['request_url'], 'Admin/Tags/add')) $msgs = $msgs.'添加客户标签';
          else if(stristr($_param['request_url'], 'Admin/Tags/edit'))  $msgs = $msgs.'修改客户标签';
          else if(stristr($_param['request_url'], 'Admin/Tags/remove')){
            $tag_id = D('Log')->str_cut('tag_id=','&ran',$_param['request_url']);
            $map['tag_id'] = array('eq',$tag_id);
            $tag_name = M('customer_tag')->where($map)->getField('tag_name');
            $msgs = $msgs.'删除客户标签'.$tag_id.'('.$tag_name.')';
          }
          else if(stristr($_param['request_url'], 'Admin/Tags/tagCustomer')) $msgs = $msgs.'客户标签关联客户信息获取';
          else if(stristr($_param['request_url'], 'Admin/Tags/removeCustomer'))  $msgs = $msgs.'删除客户标签的关联客户';
            //View360
          else if(stristr($_param['request_url'], 'Admin/view360/inputBlur')){
            $customer_id = D('Log')->str_cut('?id=','&phone',$_param['request_url']);
            $map['customer_id'] = array('eq',$customer_id);
            $customer_name = M('Customer')->where($map)->getField('nickname');
            if(strpos($_param['request_url'], 'id'))
              $msgs = $msgs.'编辑客户:'.$customer_id.'('.$customer_name.')的详情信息';
            else $msgs = $msgs.'编辑客户信息';
          }
          else if(stristr($_param['request_url'], 'Admin/View360/addContact')) $msgs = $msgs.'添加客户沟通信息';
          else if(stristr($_param['request_url'], 'Admin/View360/editContact'))  $msgs = $msgs.'编辑客户沟通信息';
          else if(stristr($_param['request_url'], 'Admin/View360/remove')) $msgs = $msgs.'删除客户沟通信息';
          else if(stristr($_param['request_url'], 'Admin/View360/buyStock')) $msgs = $msgs.'为客户添加股票推荐';
            //产品报价管理
          else if(stristr($_param['request_url'], 'Admin/ProductPrice/product_price_add')) $msgs = $msgs.'报价管理添加';
          else if(stristr($_param['request_url'], 'Admin/ProductPrice/save_product_price'))  $msgs = $msgs.'修改报价';
          else if(stristr($_param['request_url'], 'Admin/Product_price/Product_price_delete')){
            $priceid_arr = explode('price_id=',$_param['request_url']);
            $map['price_id'] = array('eq',$priceid_arr[1]);
            $product_price_name = M('product_price')->where($map)->getField('name');
            if(strpos($_param['request_url'], 'price_id'))
              $msgs = $msgs.'删除报价:'.$priceid_arr[1].'('.$product_price_name.')';
            else $msgs = $msgs.'删除报价';
          }
            //续费客户管理
          else if(stristr($_param['request_url'], 'Admin/Xufei/Check_Tag')){
            $customer_id = D('Log')->str_cut('?customer_id=','&arr',$_param['request_url']);
            $arraytag_arr = D('Log')->str_cut('array_tag=','&user',$_param['request_url']);
            $array_tag = explode(',',$arraytag_arr);
            $msgs = $msgs.'修改客户'.$customer_id.'的标签为';
            for($i=0;$i<count($array_tag);$i++){
              $maps['tag_id'] = array('eq',$array_tag[$i]);
              $tagname_arr[] = M('customer_tag')->where($maps)->getField('tag_name');
              $msgs = $msgs.$tagname_arr[$i].'、'; //修改的标签用、分割
            }
            $msgs = substr($msgs,0,strlen($msgs)-1); //去掉最后一个、

          }
          else if(stristr($_param['request_url'], 'Admin/Xufei/ChangeCustomerType')){
            $customer_id = D('Log')->str_cut('&customer_id=','&m',$_param['request_url']);
            $map['customer_id'] = array('eq',$customer_id);
            $customer_name = M('customer')->where($map)->getField('nickname');
            $new_type = D('Log')->str_cut('&new_type=','&cus',$_param['request_url']);
            $mount_arr = explode('mount=',$_param['request_url']);
            $mount = $mount_arr[1];
            if($new_type==1)  $new_typename='新资源';
            else if($new_type==2) $new_typename='A类资源';
            else if($new_type==3) $new_typename='B类资源';
            else if($new_type==4) $new_typename='C类资源';
            else if($new_type==5) $new_typename='D类资源';
            else if($new_type==6) $new_typename='定金客户';
            else if($new_type==7) $new_typename='完款客户';
            else $new_typename='Z类客户';
            $msgs = $msgs.'客户'.$customer_id.'('.$customer_name.')更改为'.$new_typename.'、资金量为'.$mount.'W';
          }
          else if(stristr($_param['request_url'], 'Admin/Xufei/AddCommunication')) $msgs = $msgs.'添加沟通记录';
            //合同管理
          else if(stristr($_param['request_url'], 'Admin/Contract/Save_Contract')) $msgs = $msgs.'合同修改';
          else if(stristr($_param['request_url'], 'Admin/Contract/New_Maintain'))  $msgs = $msgs.'更改报价维护';
          else if(stristr($_param['request_url'], 'Admin/Contract/Contract_Cancel')){
            $contractid_arr = explode('contract_id=',$_param['request_url']);
            $map['contract.contract_id'] = array('eq',$contractid_arr[1]);
            $contract_info = M('Contract')->field('contract.customer_id,customer.nickname')
                            ->join('customer on customer.customer_id=contract.customer_id')->where($map)->find();
            if(strpos($_param['request_url'], 'contract_id'))
              $msgs = $msgs.'取消客户：'.$contract_info['nickname'].'的合同';
            else $msgs = $msgs.'取消合同';
          }
          else if(stristr($_param['request_url'], 'Admin/Contract/View_Message'))  $msgs = $msgs.'修改查看合同';
          else if(stristr($_param['request_url'], 'Admin/Contract/Print_Message')) $msgs = $msgs.'修改打印邮寄';
            //渠道管理
          else if(stristr($_param['request_url'], 'Admin/Source/add'))   $msgs = $msgs.'添加渠道';
          else if(stristr($_param['request_url'], 'Admin/Source/edit'))  $msgs = $msgs.'修改渠道';
          else if(stristr($_param['request_url'], 'Admin/Source/remove')){
            $sourceid_arr = explode('id=',$_param['request_url']);
            $map['source_id'] = array('eq',$sourceid_arr[1]);
            $source_name = M('Source')->where($map)->getField('name');
            $msgs = $msgs.'删除渠道'.$sourceid_arr[1].'('.$source_name.')';
          }
            //客户投诉
          else if(stristr($_param['request_url'], 'Admin/Complain/del')){
            $complainid_arr = explode('id=',$_param['request_url']);
            $map['complain_id'] = array('eq',$complainid_arr[1]);
           // $complain_info = M('customer_complain')->where($map)->find();
            $msgs = $msgs.'删除投诉记录:'.$complainid_arr[1];//'('.$complain_info['title'].')';
          }
          else if(stristr($_param['request_url'], 'Admin/Complain/edit')){
            $complainid = D('Log')->str_cut('complain_id=','&s',$_param['request_url']);
            $state_arr = explode('state=',$_param['request_url']);
            $state = $state_arr[1];
            $map['complain_id'] = array('eq',$complainid);
            //$complain_info = M('customer_complain')->where($map)->getField('title');
            if($state==0)  $state_name = '未处理';
            else if($state=='1')  $state_name = '处理中';
            else if($state=='2')  $state_name = '已处理';
            else if($state=='3')  $state_name = '已挂起';
            $msgs = $msgs.'投诉记录:'.$complainid.' 修改为'.$state_name.'状态'; // ('.$complain_info.')
          }
          else if(stristr($_param['request_url'], 'Admin/Complain/add')) $msgs = $msgs.'添加投诉';
            //审核
          else if(stristr($_param['request_url'], 'Admin/Money/excel_runexport')){
            $createtime = D('Log')->str_cut('?createtime=','&',$_param['request_url']);
            $endtime = D('Log')->str_cut('endtime=','&checkperson',$_param['request_url']);
            $checkper_arr = explode('checkperson=',$_param['request_url']);
            $map['user_id'] = $checkper_arr[1];
            $nickname = M('User')->where($map)->getField('nickname');
            $msgs = $msgs.'员工编号:'.$checkper_arr[1].'('.$nickname.')'.'导出'.$createtime.'到'.$endtime.'的查账';
          }
          else if(stristr($_param['request_url'], 'Admin/Money/verify')){
            $payrecord_id = D('Log')->str_cut('?id=','&info',$_param['request_url']);
            $mapp['payrecord_id'] = array('eq',$payrecord_id);
            $paytype_arr = explode('paytype=',$_param['request_url']);
            $pay_type = $paytype_arr[1];
            $audit_res = D('Log')->str_cut('identify=','&pay',$_param['request_url']);
            $payrecord_info = M('payrecord')->where($mapp)->find();
            if($pay_type=='1') $pay_names='新单';
            else if($pay_type=='2') $pay_names='续费';
            else if($pay_type=='3') $pay_names='退款';
            if($audit_res=='0') $audit_name='待审核';
            else if($audit_res=='1') $audit_name='审核成功';
            else if($audit_res=='2') $audit_name='审核失败';
            $msgs = $msgs.'审核'.$payrecord_info['pay_name'].'的';
            $msgs = $msgs.$pay_names.'为'.$audit_name.'状态';
          }
            //OM配置
          else if(stristr($_param['request_url'], 'Admin/Om/editom'))    $msgs = $msgs.'修改OM配置';
          else if(stristr($_param['request_url'], 'Admin/Om/addOmconfig')){
            $bindperson = D('Log')->str_cut('?bindperson=','&subt',$_param['request_url']);
            $subtelphone = D('Log')->str_cut('subtelphone=','&add',$_param['request_url']);
            $msgs = $msgs.'为'.$bindperson.'添加'.$subtelphone.'分机配置';
          }
          else if(stristr($_param['request_url'], 'Admin/Om/editphone')) $msgs = $msgs.'修改分机配置';
            //我的查账管理
          else if(stristr($_param['request_url'], 'Admin/pays/addnew'))  $msgs = $msgs.'添加新单查账';
          else if(stristr($_param['request_url'], 'Admin/pays/addxufei'))  $msgs = $msgs.'添加续费查账';
          else  $msgs = '';


        $res = array('rcode'=>0,'data'=>false,'msg'=>'ok');
        $userlog_data = array();
        $wheres = array();
        $maps = array();
        $map = array();
        $MUserLog = M('Userlog');
        $MUser = M('User');

        $userlog_data['user_id'] = $_param['uid'];
        $wheres['user_id'] = $userlog_data['user_id'];
        //获取用户基本信息
        $uinfo = $MUser->field("user_id,nickname,sector_id,role_id")->where($wheres)->find();
        $userlog_data['user_name'] = $uinfo['nickname'];
        $userlog_data['user_sector'] = $uinfo['sector_id'];
        $userlog_data['user_role'] = $uinfo['role_id'];
        $userlog_data['create_time'] = date('Y-m-d H:i:s');
        $userlog_data['type'] = strtolower(CONTROLLER_NAME);
        $userlog_data['request_url'] = $_param['request_url'];
        $userlog_data['request_method'] = $_param['request_method'];
        $userlog_data['request_data'] = $_param['request_data'];
        if($msgs){
            $userlog_data['msg'] = $msgs;
            //存入操作日志表userlog
            $addsta = $MUserLog -> data($userlog_data) ->add();
            if($addsta) {
                return true;
            }else{
                return false;
            }
        } else return false;
    }
}

